import 'package:flutter/material.dart';
import 'package:management/model/department_model.dart';

///修改被访部门
class SetDepartment extends StatefulWidget {
  final List<Department>? departmentSource;

  const SetDepartment({Key? key, required this.departmentSource}) : super(key: key);

  @override
  _SetDepartmentState createState() => _SetDepartmentState();
}

class _SetDepartmentState extends State<SetDepartment> {
  late List<Department> departmentSource;

  @override
  void initState() {
    super.initState();
    if (widget.departmentSource == null) {
      departmentSource = [];
    } else {
      departmentSource = widget.departmentSource!;
    }
  }

  @override
  void dispose() {
    DepartmentProvider().close();
    super.dispose();
  }

  _buildBody() {
    return SingleChildScrollView(
      child: Container(
        child: PaginatedDataTable(
          header: Divider(),
          actions: [
            IconButton(
                onPressed: () {
                  addDepartment(context);
                },
                icon: Icon(
                  Icons.add,
                  size: 50,
                )),
            IconButton(
                onPressed: () {
                  deleteDepartment();
                },
                icon: Icon(
                  Icons.delete,
                  size: 50,
                )),
          ],
          columns: [DataColumn(label: Text("名称"))],
          source: DepartmentDataSource(departmentSource),
          onSelectAll: (all) {
            departmentSource.forEach((element) {
              element.selected = all;
            });
            setState(() {});
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "被访部门",
          style: TextStyle(fontSize: 30),
        ),
        centerTitle: true,
      ),
      body: _buildBody(),
    );
  }

  void addDepartment(BuildContext context) async {
    final TextEditingController departmentCtl = TextEditingController();
    GlobalKey<FormState> key = GlobalKey();
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: SingleChildScrollView(
              child: Form(
                key: key,
                child: Container(
                  width: 100,
                  height: 60,
                  child: TextFormField(
                    controller: departmentCtl,
                    validator: (value) {
                      if (value!.isEmpty) {
                        return "不能为空";
                      }
                      return null;
                    },
                    decoration: InputDecoration(hintText: "请输入部门名称"),
                  ),
                ),
              ),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    key.currentState!.save();
                    if (key.currentState!.validate()) {
                      departmentSource.add(Department(departmentCtl.text));
                      DepartmentProvider()
                          .insert(Department(departmentCtl.text));
                      setState(() {});
                      Navigator.pop(context);
                    }
                  },
                  child: Text("添加")),
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消")),
            ],
          );
        });
  }

  void deleteDepartment() async {
    List<Department> deleteDepartments = [];
    departmentSource.forEach((element) {

      if (element.selected!) {
        deleteDepartments.add(element);
      }
    });
    var departmentProvider = DepartmentProvider();
    await departmentProvider.open();
    deleteDepartments.forEach((element) {
      departmentSource.remove(element);
      departmentProvider.delete(element);
    });
    setState(() {});
  }
}

class DepartmentDataSource extends DataTableSource {
  final List<Department> data;

  DepartmentDataSource(this.data);

  @override
  DataRow? getRow(int index) {
    if (index > data.length) {
      return null;
    }
    return DataRow.byIndex(
      index: index,
      selected: data[index].selected!,
      onSelectChanged: (selected) {
        data[index].selected = selected;
        notifyListeners();
      },
      cells: [
        DataCell(
          Text(
            "${data[index].name}",
            style: TextStyle(fontSize: 30, fontStyle: FontStyle.italic),
          ),
        ),
      ],
    );
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => data.length;

  @override
  int get selectedRowCount => 0;
}
